package com.sita.bluetactivity.MineFragment;

import android.Manifest;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.sita.bluetactivity.Base.BaseActivity;
import com.sita.bluetactivity.Base.BaseApplication;
import com.sita.bluetactivity.Base.BaseValue;
import com.sita.bluetactivity.Base.SpUtils;
import com.sita.bluetactivity.Base.ToastUtils;
import com.sita.bluetactivity.MyClass.BindVehicle;
import com.sita.bluetactivity.MyClass.BindVehicleDao;
import com.sita.bluetactivity.MyClass.DaoSingleTon;
import com.sita.bluetactivity.NewBlueTooth.BindBackBean;
import com.sita.bluetactivity.NewBlueTooth.BindVehicleMsg;
import com.sita.bluetactivity.NewBlueTooth.BtService;
import com.sita.bluetactivity.R;
import com.sita.bluetactivity.http.RestClient;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

import static android.Manifest.permission.ACCESS_FINE_LOCATION;
import static android.Manifest.permission.BLUETOOTH_ADMIN;

/**
 * Created by Jason on 2016/10/10.
 */

public class BindVehicleActivity extends BaseActivity implements View.OnClickListener,ItemClickListener {
    private RecyclerView vehicle_list;
    private ImageView add;
    private LinearLayout back;
    private TextView headTitle;
    private BindVehicleAdapter adapter;
    private BindVehicleMsg bindVehicleMsg;
    /***********************************/
    private BtService.BtBinder  btBinder;
    private Intent intentService;
    private ConnectSuccessBroad connectSuccessBroad = new ConnectSuccessBroad();
    private BindVehicleDao bindVehicleDao;
    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            btBinder = (BtService.BtBinder) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };
    /**********************************************************
     * 88/
     * 蓝牙搜索回调
     */

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        IntentFilter filter = new IntentFilter();
        filter.addAction("com.sita.bluetactivity.ISOK");
        registerReceiver(connectSuccessBroad,filter);
        intentService = new Intent(this, BtService.class);
        bindService(intentService, connection, BIND_AUTO_CREATE);

    }

    /*****************************************************************/
    @Override
    protected void initData() {
        headTitle.setText("我的车辆");
        back.setVisibility(View.VISIBLE);
        back.setOnClickListener(this);
        add.setOnClickListener(this);

        bindVehicleDao =  DaoSingleTon.getInstance().getBindVehicleDao();

    }

    @Override
    protected void onStart() {
        super.onStart();
        getBindList();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        getBindList();
    }

    private void getBindList(){
        BindListRequest request = new BindListRequest();
        request.user_id = SpUtils.getString("AccountId",null,BaseApplication.getContext());
        RestClient.getRestService().bindVehicleList(request, new Callback<BindListBackBean>() {
            @Override
            public void success(BindListBackBean backBean, Response response) {
                adapter.getData(backBean.getData());
                saveVehicleData(backBean);
            }

            @Override
            public void failure(RetrofitError error) {
                //获取失败从数据库中获取数据

                adapter.getData(data());

            }
        });

    }
    private void saveVehicleData(BindListBackBean backBean){

        bindVehicleDao.deleteAll();//先删除数据库，在添加，保证每次数据最新
        BindVehicle bindVehicle = new BindVehicle();
        if (backBean.getData()!=null){
            for (int i=0;i<backBean.getData().size();i++){
                bindVehicle.setBodaoid(backBean.getData().get(i).getBodaoid());
                bindVehicle.setUser_id(backBean.getData().get(i).getUser_id());
                bindVehicle.setController_pass(backBean.getData().get(i).getController_pass());
                bindVehicle.setController_address(backBean.getData().get(i).getController_address());
                bindVehicle.setController_id(backBean.getData().get(i).getController_id());
                bindVehicle.setTime(backBean.getData().get(i).getTime());
                bindVehicle.setIsselect(String.valueOf(backBean.getData().get(i).getIsselect()));
                bindVehicleDao.insertOrReplace(bindVehicle);//替换的方法
                bindVehicleDao.insertInTx();
            }
        }


    }
    private List<BindListBackBean.DataBean> data(){
        List<BindVehicle> bindVehicle = bindVehicleDao.queryBuilder().list();
        List<BindListBackBean.DataBean> dataBeens = new ArrayList<>();
        BindListBackBean.DataBean dataBeen= new BindListBackBean.DataBean();
        for (int i=0;i<bindVehicle.size();i++){
            dataBeen.setUser_id(bindVehicle.get(i).getUser_id());
            dataBeen.setController_id(bindVehicle.get(i).getController_id());
            dataBeen.setController_address(bindVehicle.get(i).getController_address());
            dataBeen.setBodaoid(bindVehicle.get(i).getBodaoid());
            dataBeen.setController_pass(bindVehicle.get(i).getController_pass());
            dataBeen.setTime(bindVehicle.get(i).getTime());
            dataBeen.setIsselect(Integer.valueOf(bindVehicle.get(i).getIsselect()));
            dataBeens.add(dataBeen);
        }
        return  dataBeens;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(connectSuccessBroad);
        unbindService(connection);

    }

    @Override
    protected void initView() {
        bindVehicleDao = DaoSingleTon.getInstance().getBindVehicleDao();
        vehicle_list = bindView(R.id.bind_vehicle_list);
        add = bindView(R.id.addVehicle);
        back = bindView(R.id.back_layout);
        headTitle = bindView(R.id.head_tx);
        vehicle_list.setLayoutManager(new LinearLayoutManager(this));
        adapter = new BindVehicleAdapter(this,this);
        vehicle_list.setAdapter(adapter);



    }
    @Override
    protected int getId() {
        return R.layout.activity_myvehicle;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.addVehicle:
          FindVehicleBtActivity.JumpIntent(this);
                break;
            case R.id.back_layout:
                finish();
                break;
        }

    }
    public static void jumpIntent(Context context){
        Intent intent = new Intent(context,BindVehicleActivity.class);
        context.startActivity(intent);
    }

    @Override
    public void onItemClick(int position) {
    //解绑的时候如果有蓝牙处于连接状态泽断开连接
        if (BaseValue.BtIsConnection) {
            btBinder.disConnected();
        }

    }





    //当连接成功以后绑定该车辆
    private class ConnectSuccessBroad extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
 ///连接成功以后将bindVehicleMsg传过来作为参数进行车辆的绑定
            bindVehicleMsg = (BindVehicleMsg) intent.getSerializableExtra("VehicleMsg");
            Log.e("sssss",bindVehicleMsg.controller_address);
            RestClient.getRestService().BindVehicleFromBt(bindVehicleMsg, new Callback<BindBackBean>() {
                @Override
                public void success(BindBackBean bindBackBean, Response response) {
                   if (bindBackBean.getData().getReturnCode()==0&&bindBackBean.getData().getBikeInfo()!=null){
                       ToastUtils.show("绑定成功",3000);
                       SpUtils.putString("BoDaoID",bindBackBean.getData().getBikeInfo().getBodaoid(),BaseApplication.getContext());

                   }
                    else {
                       ToastUtils.show(bindBackBean.getData().getReturnInfo(),3000);
                   }
                }
                @Override
                public void failure(RetrofitError error) {
                    Log.e("xxxxxx",error.toString());
                }
            });
        }
    }


}
